import os
import requests


def download_images_from_github_repo(owner, repo_name, save_dir):
    api_url = f"https://api.github.com/repos/{owner}/{repo_name}/contents/"
    headers = {"Accept": "application/vnd.github.v3+json"}

    # 获取仓库根目录内容
    response = requests.get(api_url, headers=headers)
    if response.status_code != 200:
        print("无法访问 GitHub 仓库。")
        return

    content_list = response.json()
    image_extensions = {".jpg", ".jpeg", ".png", ".gif"}

    # 遍历根目录内容
    for content in content_list:
        if "download_url" in content and os.path.splitext(content["name"])[1] in image_extensions:
            download_url = content["download_url"]
            file_name = os.path.join(save_dir, content["name"])

            # 下载图片
            download_image(download_url, file_name)


def download_image(url, file_path):
    response = requests.get(url)

    if response.status_code == 200:
        with open(file_path, "wb") as f:
            f.write(response.content)
        print(f"已下载图片：{file_path}")
    else:
        print(f"无法下载图片：{url}")


if __name__ == "__main__":
    # 替换成您要爬取的 GitHub 仓库信息
    owner = "Snailclimb"
    repo_name = "JavaGuide"
    save_directory = "D:/project/pythonproject/game_and_utils/py-file/img"

    download_images_from_github_repo(owner, repo_name, save_directory)
